/**
 * @Project Name:cn.hoofungson.studio
 * @Package Name:cn.hoofungson.sso.service
 * @Since JDK 1.8
 */
package cn.hoofungson.sso.service;

import cn.hoofungson.service.generic.service.impl.GenericServiceImpl;
import cn.hoofungson.sso.config.Constant;
import cn.hoofungson.sso.model.User;
import cn.hoofungson.sso.service.common.JwtService;
import cn.hoofungson.sso.util.JwtUtil;
import cn.hoofungson.sso.util.ResponseUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 用户业务实现
 * @Author 胡松 hoofungson@163.com
 * @Date 2017-11-10 21:12
 * @Version V1.0
 */
@Service
@Transactional
public class UserServiceImpl extends GenericServiceImpl implements UserService {

    private static final Logger logger = LogManager.getLogger(UserServiceImpl.class);

    @Autowired
    private JwtService jwtService;

    /**
     * 用户登录
     *
     * @param request
     * @param response
     * @param user
     * @return
     **/
    @Override
    public ResponseEntity<String> login(HttpServletRequest request, HttpServletResponse response, User user) {
        try {
            if(!"admin".equals(user.getName()) || !"123456".equals(user.getPassword())){
                return ResponseUtil.exception("账号或者密码错误");
            }
            user.setRoleId(1L);
            String subject = JwtUtil.generalSubject(user);
            String token = jwtService.createJWT(Constant.JWT_ID, subject, Constant.JWT_TTL);
            String refreshToken = jwtService.createJWT(Constant.JWT_ID, subject, Constant.JWT_REFRESH_TTL);
            JSONObject jo = new JSONObject();
            jo.put("token", token);
            jo.put("refreshToken", refreshToken);
            return ResponseUtil.success(jo);
        } catch (Exception e) {
            logger.error(e);
            return ResponseUtil.unKonwException();
        }
    }
}
